import json
import os

from flask import jsonify, Blueprint, request

from db import db1
from utlis.acl import acll
from utlis.comm import get_data
from utlis.jwt_token import myjwt
from utlis.myfiles import myf
from utlis.redisconn import r

bp_user = Blueprint('users',__name__)






#获取角色
@bp_user.route('/position')
def position():
    sql = """select * from position"""
    res = db1.find_all(sql)
    return jsonify({'code':200,"list":res})

#获取岗位
@bp_user.route('/jobsM')
def jobsM():
    sql = """select * from jobs"""
    res = db1.find_all(sql)
    return jsonify({'code':200,"list":res})

##图片上传
@bp_user.route('/picM',methods = ['GET','POST'])
def picM():
    if request.method == 'POST':
        file = request.files['file']
        newname = myf.rename(file.filename)
        file.save(os.path.join('./static/picture/' + newname))
        return jsonify({'code': 200, 'pic': newname})

##添加用户
@bp_user.route('/add_userM',methods = ['GET','POST'])
def add_userM():
    if request.method == 'POST':
        data = get_data()
        sql = """insert into user(usernum,comany_id,gender,moble,username,jobnum,jobs_id,pic,email,position_id,entity) values('%s',%d,%d,'%s','%s','%s',%d,'%s','%s',%d,%d)"""%(data['usernum'],int(data['comany_id']),int(data['gender']),data['mobile'],data['username'],data['jobnum'],int(data['jobs_id']),data['pic'],data['email'],int(data['position_id']),int(data['entity']))
        db1.insert(sql)
        print(sql)
        return jsonify({'code':200})
    #展示用户信息
    else:
        sql1 = """select * from user"""
        res = db1.find_all(sql1)
        return jsonify({'copde':200,"list":res})

#登录资源配置
@bp_user.route('/loginM',methods = ['POST','GET'])
def loginM():
    if request.method == 'POST':
        data = get_data()
        sql = """select * from user where usernum = '%s'"""%(data['username'])
        res = db1.find_one(sql)
        if res:
            if res['username'] == data['password']:
                userid = res['id']
                token = myjwt.jwt_encode({'data':{'userid':res['id']}})
                ress = acll.get_vue(userid)
                # 把url存入redis,
                r.insert_set('users'+str(userid),ress)
                aa = r.find_set('users'+str(userid))
                print(aa)
                return jsonify({'code':200,"mes":"登陆成功","token":token,'userid':userid,"url":aa})
            else:
                return jsonify({'code': 20021, "mes": "密码错误"})
        else:
            return jsonify({'code': 20021,"mes":"账户不存在"})


##获取角色
@bp_user.route('/roleM')
def roleM():
    sql = """select * from role"""
    res = db1.find_all(sql)
    return jsonify({'code':200,"list":res})

#给用户配置角色
@bp_user.route('/add_roles',methods = ['POST','GET'])
def add_roles():
    if request.method == 'POST':
        data = get_data()
        rlist = json.loads(data['rid'])
        #查找用户有什么角色
        sql = """select * from user_role where userid = 1"""
        res = db1.find_all(sql)
        ulist = []
        for i in res:
            ulist.append(i['roleid'])
        # print(ulist)
        if rlist:
            sql2 = """delete from user_role where userid = 1"""
            db1.insert(sql2)
            for j in rlist:
                sql3 = """insert into user_role(userid,roleid) values(%d,%d)"""%(1,int(j))
                db1.insert(sql3)
            return jsonify({'code': 200})
        else:
            return jsonify({'code':1001})


#hash的测试
@bp_user.route('/test1')
def test1( ):
    key = 'abac '
    r.insert_hash(key, ' ip', '127.0.0.1')
    r.insert_hash(key, ' level', ' 003')
    r.insert_hash(key, 'time ', "[ '2021-10-10', '2021-12-10']")
    values = r.get_all_hash(key)
# print(type(values))
    for (k,v) in values.items():
        if str(k, encoding='utf8') == 'time ':
            print(eval(v))
            print(eval(v)[0])
            print(eval(v)[1])
    return 'ok'


@bp_user.route('/workM',methods = ['POST','GET'])
def workM():
    if request.method == 'POST':
        data = get_data()
        print(data['name'])
        print(data)
        return jsonify({'code':200})

@bp_user.route('/workfM')
def workfM():
    sqs = """select * from workflow"""
    res = db1.find_all(sqs)
    return jsonify({'code':200,"list":res})
#获取请假接口
@bp_user.route('/worklist')
def worklist():
    sql = "select * from workflow"
    res = db1.find_all(sql)
    return jsonify({"code":200,'list':res})

#获取数据源接口
@bp_user.route('/getresourcedata')
def getresourcedata():
    #从redis取，如果有直接返回
    values = r.get_str('dataresouce')
    if values:
        list = eval(values)
    else:
        #如果没有查询
        sql = """select * from data_source"""
        res = db1.find_all(sql)
        list = []
        if res:
            for i in res:
                dict={'id':i['id'],'name':i['name']}
                sql1 = """select id,name,type from %s"""%(i['tablename'])
                print(sql1)
                subres = db1.find_all(sql1)
                dict['mes'] = subres
                list.append(dict)
        #存入redis
        r.set_str('dataresouce',json.dumps(list))
    return jsonify({"code":200,'list':list})


# 添加请假
@bp_user.route('/add_workflow',methods=['POST','GET'])
def add_workflow():
    if request.method == 'POST':
        data = get_data()
        id = data['id']
        list = json.loads(data['list'])
        sql = """select * from workflow where id = %d"""%(int(id))
        res = db1.find_one(sql)
        list1 = str(list[1]['values'])
        print(list1)
        if res:
            sql1 = """update workflow set params = "%s" where id = %d"""%(list1,int(id))
            print(sql1)
            # db1.insert(sql1)
            return jsonify({'code':200})
        else:
            return jsonify({'code':10010})


        # return jsonify({'code':200})



















